<?php
namespace Controllers;

use Models\Book;
use Models\Record;
use Models\Student;

class RecordController extends BaseController {

    /**
     * 创建借阅记录
     */
    public function add() {
        if ($_POST) {
            $book_id = $_POST['book_id'];
            $number = isset($_POST['number']) ? $_POST['number'] : '';
            if (empty($number)) return $this->error('学号必须填写');
            $studentModel = new Student();
            $student = $studentModel->getStudentByNumber($number);
            if (empty($student)) return $this->error('学生不存在');
            $borrow_time = date('Y-m-d H:i:s', time());
            // 事务：一个任务中，涉及若干个对数据库的写操作，要么全部成功 要么全部失败   开启事务，回滚事务，提交事务
            $recordModel = new Record();
            $bookModel = new Book();
            $book = $bookModel->getBookById($book_id);
            // 开启事务
            $bookModel->pdo->beginTransaction();

            if (!$recordModel->addRecord($student['id'], $book_id, $borrow_time)) {
                $bookModel->pdo->rollBack();
                return $this->error('借阅记录生成失败');
            }
            $stock = $book['stock'] - 1;
            if (!$bookModel->decrementStock($stock, $book_id)) {
                $bookModel->pdo->rollBack();
                return $this->error('库存更新失败');
            }

            $bookModel->pdo->commit();
            return $this->success('借阅成功', '/index.php?c=book&a=lists');



        } else {
            $book_id = $_GET['book_id'];
            if (empty($book_id)) return $this->error('图书参数错误');
            $bookModel = new Book();
            $book = $bookModel->getBookById($book_id);
            if (empty($book)) return $this->error('图书不存在');
            if ($book['stock'] <= 0) return $this->error('图书库存不足');
            return $this->render('record/add', ['book' => $book]);

        }
    }

}